/*
 * Copyright (C) 2010 Michael Pardo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.activeharmony.sample;

import com.activeharmony.query.Set;
import com.activeharmony.query.Update;

import com.activeharmony.sample.slice.Details;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * UpdateTest Class
 */
public class UpdateTest extends  SqlableTestCase {
    private static final String UPDATE_PREFIX = "UPDATE Details ";

    /**
     * testUpdate method that checks the update()
     */
    @Test
    public void testUpdate() {
        assertSqlEquals(UPDATE_PREFIX, update());
    }

    /**
     * testUpdateSet method that checks the set()
     */
    @Test
    public void testUpdateSet() {
        assertSqlEquals(UPDATE_PREFIX + "SET Id = 5 ",
                update().set("Id = 5"));
    }

    /**
     * testUpdateWhereNoArguments method that checks the where sql
     */
    @Test
    public void testUpdateWhereNoArguments() {
        assertSqlEquals(UPDATE_PREFIX + "SET Id = 5 WHERE Id = 1 ",
                update()
                    .set("Id = 5")
                    .where("Id = 1"));
    }

    /**
     * testUpdateWhereWithArguments method that checks where with sql
     */
    @Test
    public void testUpdateWhereWithArguments() {
        Set set = update()
                .set("Id = 5")
                .where("Id = ?", 2);
        assertArrayEquals(set.getArguments(), "2");
        assertSqlEquals(UPDATE_PREFIX + "SET Id = 5 WHERE Id = ? ",
                set);

        set = update()
                .set("Id = 5")
                .where("Id = ?", 2)
                .where("Id IN (?, ?, ?)", 5, 4, 3);
        assertArrayEquals(set.getArguments(), "5", "4", "3");
        assertSqlEquals(UPDATE_PREFIX + "SET Id = 5 WHERE Id IN (?, ?, ?) ",
                set);
    }

    private Update update() {
        return new Update(Details.class);
    }

    /**
     * assertArrayEquals
     *
     * @param actual actual
     * @param expected expected
     */
    public <T> void assertArrayEquals(T[] actual, T... expected) {
        assertEquals(expected.length, actual.length);

        for (int i = 0; i < expected.length; i++) {
            assertEquals(expected[i], actual[i]);
        }
    }
}
